<!--
  * 微信回复用户
-->
<template>
  <a-modal
    :title="'商家处理'"
    :width="1000"
    :open="openForm"
    @cancel="onReplyModalClose"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="onReplySubmit"
  >
    <a-form :model="replyForm" ref="formRef" :rules="rules">
      <group-title class="pb-0.5">基本信息</group-title>
      <a-form-item label="是否退款" name="isRefund">
        <!-- <a-checkbox-group :value="replyForm.isRefund" :options="YES_OR_NO" @change="changeIsRefund" /> -->
        <a-radio-group v-model:value="replyForm.isRefund" :options="YES_OR_NO" @click="changeIsRefund" />
      </a-form-item>
      <template v-if="replyForm.isRefund == '1'">
        <a-form-item label="退款金额" name="isRefund" v-if="props.rowData?.refundAmt">
          {{ formatToMoney(props.rowData?.refundAmt / 100) }}元</a-form-item
        >
        <div class="p-b-4">
          <OrderList :row-data="props.rowData" />
        </div>
      </template>
      <template v-else-if="replyForm.isRefund == '0'">
        <a-form-item label="驳回理由" name="rejectReason">
          <a-textarea v-model:value="replyForm.rejectReason" :rows="4" placeholder="请输入驳回理由，限200个汉字" :maxlength="200" />
        </a-form-item>
        <a-form-item label="图片">
          <div class="upload-list">
            <div class="upload-item">
              <a-upload
                v-model:fileList="replyForm.rejectMediaList"
                :customRequest="(file) => uploadFunc(file, 'rejectMediaList')"
                :multiple="false"
                :maxCount="4"
                :accept="limitUpload['rejectMediaList'].fileType.toString()"
                :showUploadList="{ showPreviewIcon: true, showRemoveIcon: true }"
                :before-upload="(file, fileList) => beforeUpload(file, fileList, 'rejectMediaList')"
                list-type="picture-card"
              >
                <div v-if="replyForm.rejectMediaList?.length < 4">
                  <plus-outlined />
                  <div style="margin-top: 8px">上传</div>
                </div>
              </a-upload>
            </div>
          </div>
        </a-form-item>
      </template>
      <template v-else>
        <a-form-item label="回复内容" name="replyContent">
          <a-textarea v-model:value="replyForm.replyContent" :rows="4" placeholder="请输入回复内容，限200个汉字" :maxlength="200" />
        </a-form-item>
        <a-form-item label="图片">
          <div class="upload-list">
            <div class="upload-item">
              <a-upload
                v-model:fileList="replyForm.responseImages"
                :customRequest="(file) => uploadFunc(file, 'responseImages')"
                :multiple="false"
                :maxCount="4"
                :accept="limitUpload['responseImages'].fileType.toString()"
                :showUploadList="{ showPreviewIcon: true, showRemoveIcon: true }"
                :before-upload="(file, fileList) => beforeUpload(file, fileList, 'responseImages')"
                list-type="picture-card"
              >
                <div v-if="replyForm.responseImages?.length < 4">
                  <plus-outlined />
                  <div style="margin-top: 8px">上传</div>
                </div>
              </a-upload>
            </div>
          </div>
        </a-form-item>
      </template>
      <group-title class="pb-0.5">协商历史</group-title>
      <WeChatHistoryList ref="historyList" :row-data="props.rowData" />
    </a-form>
    <template #footer>
      <a-space v-if="replyForm.isRefund != '1'">
        <a-button @click="onReplyModalClose">取消</a-button>
        <a-button type="primary" @click="onReplySubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import { message, Modal, Upload } from 'ant-design-vue'
  import { wechatUpload, wechatReply, wechatRefund } from '/@/api/business/b-merchant/complaintManage'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { getObjValue, setObjValue, formatToMoney, strToArr } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import WeChatHistoryList from './wechat-history-list.vue'
  import OrderList from './order-list.vue'
  import { cloneDeep, isEmpty } from 'lodash-es'
  import {
    YES_OR_NO, //是否
  } from '/@/constants/dict'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  // ------------------------ 事件 ------------------------

  const formApi = {
    reply: wechatReply,
    complete: wechatRefund,
  }
  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
    apiType: {
      type: String,
      default: 'reply',
    },
  })
  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  const _apiType = ref()
  // 切换是否退款
  function changeIsRefund(e) {
    if (!e.target.value) return
    let value = e.target.value
    if (value == replyForm.value.isRefund) {
      replyForm.value.isRefund = undefined
    }
    console.log(replyForm.value.isRefund, isEmpty(replyForm.value.isRefund))

    // if (replyForm.value.isRefund) _apiType.value = replyForm.value.isRefund ? 'refund' : 'pay'
  }

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示

  function show(rowData) {
    console.log('show===>', rowData)

    // 初始化查询
    const { complaintNo, merchantId, channelIds } = rowData
    let channelIdArr = strToArr(channelIds)
    if (!complaintNo) return message.error('投诉单号不能为空')
    if (!merchantId) return message.error('投诉商户id不能为空')
    if (!channelIdArr || channelIdArr.length == 0) return message.error('支付通道id不能为空')
    replyForm.value.complaintId = complaintNo
    replyForm.value.merchantId = merchantId //'02VA2P2J02E57' //
    replyForm.value.channelId = channelIdArr[0] //'02TD361I30DND' //
  }

  // 回复用户弹窗相关
  const infoForm = {
    complaintId: undefined, //投诉单id
    isRefund: undefined, //是否退款

    merchantId: null, //商户id
    channelId: null, //通道id
    replyContent: '', //回复内容
    responseImages: [], //回复图片列表

    // 拒绝表单
    action: 'REJECT', //拒绝
    rejectReason: undefined, //拒绝理由
    rejectMediaList: [], //拒绝图片列表
  }
  const replyForm = ref(cloneDeep(infoForm))

  const formRef = ref()
  const rules = ref({
    replyContent: [
      {
        required: true,
        message: '请输入回复内容',
        trigger: 'blur',
      },
    ],
    rejectReason: [
      {
        required: true,
        message: '请输入驳回理由',
        trigger: 'blur',
      },
    ],
  })
  // 提交回复用户
  async function onReplySubmit() {
    console.log('onReplySubmit', replyForm.value)

    formRef.value.validate().then(async () => {
      const { complaintId, merchantId, channelId, replyContent, responseImages, action, rejectReason, rejectMediaList } = cloneDeep(replyForm.value)
      let data = {}
      SmartLoading.show()
      try {
        if (replyForm.value.isRefund == '0') {
          _apiType.value = 'complete'
          data = {
            complaintId,
            action,
            rejectReason,
            rejectMediaList: rejectMediaList.map((item) => item.response.data),
          }
        } else {
          _apiType.value = 'reply'
          data = {
            complaintId,
            merchantId,
            channelId,
            replyContent,
            responseImages: responseImages.map((item) => item.response.data),
          }
        }
        let res = await formApi[_apiType.value](data)
        if (res.code === 200) {
          message.success('回复成功')
          emit('ok')
          onReplyModalClose()
        }
      } catch (error) {
        console.log(error)

        // message.error(error)
      }
      SmartLoading.hide()
    })
  }

  const limitUpload = {
    responseImages: {
      fileType: ['.jpg', '.BMP', '.png', '.jpeg', '.pdf'],
      fileSize: 2,
    },
    rejectMediaList: {
      fileType: ['.jpg', '.BMP', '.png', '.jpeg', '.pdf'],
      fileSize: 2,
    },
  }
  // 上传前拦截
  const beforeUpload = (file, fileList, field) => {
    // 校检文件类型
    if (limitUpload[field].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[field].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[field].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[field].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[field].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[field].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // let formData = new FormData()
    // formData.append('file', file.file)
    // try {
    //   const res = await wechatUpload(formData)
    //   console.log('微信上传res===>', res)
    //   // if (res.code === 200 && res.data) {
    //   //   fileList.value.push(res.data)
    //   // }
    // } catch (error) {
    //   proxy.$modal.msgError(error)
    // }
    const response = await myUpload(file)

    if (response?.res?.url) {
      wechatUpload({
        fileUrl: response?.res?.url,
        fileName: response?.res?.fileName,
        merchantId: props.rowData.merchantId,
      })
    }
  }

  function onReplyModalClose() {
    replyForm.value = cloneDeep(infoForm)
    openForm.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  defineExpose({
    show,
  })
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
